package com.coderli.onecoder.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coderli.onecoder.server.handler.AgentMessageHandler;
import com.coderli.onecoder.server.handler.HandlerFactory;

public class HypervisorServerHandler extends SimpleChannelHandler {

	private static final Logger log = LoggerFactory
			.getLogger(HypervisorServerHandler.class);

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		log.info("Server has connected to client now.");
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		log.info("Ok I have recieve your message.");
		Object obj = e.getMessage();
		AgentMessageHandler handler = HandlerFactory.getMessageHandler(obj);
		handler.handleMessage(e);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		log.error("Unexpected exception from downstream.", e.getCause());
		e.getChannel().close();
	}
}
